package com.gosophia.commons.ws.interceptor;

import java.util.Arrays;

import javax.xml.ws.WebServiceException;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//FIXME:移到gosophia-commons包下，与异常体系整合

/**
 * 用于拦截webservice异常，并记录日志
 * 用法：在ws实现工程的moducontext.xml中加入如下配置：
 * {@code <aop:aspectj-autoproxy />
    <bean id="exceptionInterceptor" class="com.gosophia.commons.ws.interceptor.ExceptionInterceptor"></bean>}
 * @author wangxinbing
 * @since 2010-09-29 Copyright (c) 2010 Gosophia corporation All Rights Reserved
 */
@Aspect
public class ExceptionInterceptor {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @SuppressWarnings("unused")
    @Pointcut("execution(* com.gosophia.*.ws.*WebService.*(..))")
    private void interceptorPoint() {
    }
    
    @AfterThrowing(pointcut = "interceptorPoint()", throwing = "ex")
    public void doBussinessDataServiceException(JoinPoint joinPoint,WebServiceException ex) {
        System.out.println("抛出异常");
        logger.error("Target Class : " + joinPoint.getTarget().getClass().getName());
        logger.error("Exception argument : " + Arrays.toString(joinPoint.getArgs())
                + " in :" + joinPoint.getSignature().getName() + "()");
        logger.error(ex.getMessage(),ex);
    }
    
    @Around("execution(* com.gosophia.*.ws.*WebService.*(..))")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable{
        //TODO 根据异常体系更改catch
        logger.info("The method " + joinPoint.getSignature().getName()
                + "() begins with " + Arrays.toString(joinPoint.getArgs()));
        try {
            Object result = joinPoint.proceed();
            logger.info("The method " + joinPoint.getSignature().getName()
                    + "() ends with " + result);
            return result;
        } catch (IllegalArgumentException e) {
            logger.error("Target Class : " + joinPoint.getTarget().getClass().getName());
            logger.error("Illegal argument "
                    + Arrays.toString(joinPoint.getArgs()) + " in "
                    + joinPoint.getSignature().getName() + "()");
            throw e;
        } catch (WebServiceException e){
            logger.error("Target Class : " + joinPoint.getTarget().getClass().getName());
            logger.error("Exception argument : " + Arrays.toString(joinPoint.getArgs())
                    + " in :" + joinPoint.getSignature().getName() + "()");
            logger.error(e.getMessage(),e);
            throw e;
        }
    }
}
